

class Room:
    def __init__(self, roomDesc, gameServer) -> None:
        self.gameServer = gameServer
        self.roomDesc = roomDesc
        self.roomId = self.gameServer.getNextRoomId()
        self.users = []
        self.state = 0 # 0 not game 1 gaming 
    

    def userJoin(self, user):
        if user not in self.users:
            self.users.append(user)
            user.room = self

    
    def userLeave(self, user):
        if user in self.users:
            if user.isGaming(): 
                self.userGameEnd(user)

            self.users.remove(user)
            user.room = None

        
    def getUsers(self):
        return self.users
    

    def getUserCount(self):
        return len(self.getUsers()) 
    

    def isUserInRoom(self, user):
        return user in self.users
    

    def gameStart(self):
        self.state = 1

        for user in self.users:
            user.gameStart()

    
    def getGamingUserCount(self):
        gamingUserCount = 0
        for user in self.users:
            if user.isGaming(): 
                gamingUserCount += 1
        return gamingUserCount
    

    def isGaming(self):
        return self.state == 1

    
    def userGameEnd(self, user):
        user.gameEnd()

        if self.getGamingUserCount() <= 0:
            self.gameEnd()

    
    def gameEnd(self):
        self.state = 0

        for user in self.users:
            user.gameEnd()
            user.cancelReady()

    
    def toDTO(self):
        data = {
            "roomId": self.roomId,
            "roomDesc": self.roomDesc,
            "state": self.state
        }

        data["users"] = []
        for user in self.users:
            data["users"].append(user.toDTO())

        return data
        